
package com.example.administrator.caigou51.activity;

import java.io.File;
import java.io.IOException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.media.ExifInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.ab.util.AbImageUtil;
import com.ab.util.AbLogUtil;
import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.global.App;
import com.example.administrator.caigou51.util.ImageUtil;
import com.example.administrator.caigou51.widget.cropperimage.CropImageView;


public class CropImageActivity extends GBaseActivity{

	//
	public final static String TagCropBitmap  ="TagCropBitmap";
    public final static int TagFromClipActivity =99;
    // Static final constants
    private static final int DEFAULT_ASPECT_RATIO_VALUES = 10;
    private static final int ROTATE_NINETY_DEGREES = 90;
    public static final String ASPECT_RATIO_X = "ASPECT_RATIO_X";
    public static final String ASPECT_RATIO_Y = "ASPECT_RATIO_Y";
    private static final int ON_TOUCH = 1;

    // Instance variables
    private int mAspectRatioX = DEFAULT_ASPECT_RATIO_VALUES;
    private int mAspectRatioY = DEFAULT_ASPECT_RATIO_VALUES;
    public static float diyScale = 0;
    Bitmap croppedImage;
    //设置是否等比正方形
    private boolean isAspectRatioXSeek = true;
    public static final String isAspectRatioXSeekTag = "isAspectRatioXSeekTag";

    // Saves the state upon rotating the screen/restarting the activity
    @Override
    protected void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        bundle.putInt(ASPECT_RATIO_X, mAspectRatioX);
        bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY);
    }

    // Restores the state upon rotating the screen/restarting the activity
    @Override
    protected void onRestoreInstanceState(Bundle bundle) {
        super.onRestoreInstanceState(bundle);
        mAspectRatioX = bundle.getInt(ASPECT_RATIO_X);
        mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y);
    }

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.cropper_activity);
        mAspectRatioX = 4;
        mAspectRatioY = 9;
        // Sets fonts for all
//        Typeface mFont = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf");
        ViewGroup root = (ViewGroup) findViewById(R.id.mylayout);
    //    setFont(root, mFont);
        setTopTitle("图片裁剪");
        getTopBar().setVisibility(View.GONE);
        // Initialize components of the app
        final CropImageView cropImageView = (CropImageView) findViewById(R.id.CropImageView);



        //Sets the rotate button
        final Button rotateButton = (Button) findViewById(R.id.Button_rotate);
        rotateButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                cropImageView.rotateImage(ROTATE_NINETY_DEGREES);
                cropImageView.post(new Runnable() {
					
					@Override
					public void run() {
						 cropImageView.onActionDown(App.getInstance().screenWidth, App.getInstance().screenHeight);
					}
				});
               
            }
        });

        cropImageView.setFixedAspectRatio(true);
        
        if (getIntent()!=null) {
 			//if (getIntent().getBooleanExtra(isAspectRatioXSeekTag, false)) {
 				float x = getIntent().getIntExtra(ASPECT_RATIO_X, DEFAULT_ASPECT_RATIO_VALUES);
 				float y =  getIntent().getIntExtra(ASPECT_RATIO_Y, DEFAULT_ASPECT_RATIO_VALUES);

                 cropImageView.setFixedAspectRatio(true);
                 diyScale= x/y;
 			//}
 		}
/*
 * 
        // Sets fixedAspectRatio
        fixedAspectRatioToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                cropImageView.setFixedAspectRatio(isChecked);
                if (isChecked) {
                    aspectRatioXSeek.setEnabled(true);
                    aspectRatioYSeek.setEnabled(true);
                } else {
                    aspectRatioXSeek.setEnabled(false);
                    aspectRatioYSeek.setEnabled(false);
                }
            }
        });

        // Sets initial aspect ratio to 10/10, for demonstration purposes
        cropImageView.setAspectRatio(DEFAULT_ASPECT_RATIO_VALUES, DEFAULT_ASPECT_RATIO_VALUES);

        // Sets aspectRatioX
        final TextView aspectRatioX = (TextView) findViewById(R.id.aspectRatioX);

        aspectRatioXSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar aspectRatioXSeek, int progress, boolean fromUser) {
                try {
                    mAspectRatioX = progress;
                    cropImageView.setAspectRatio(progress, mAspectRatioY);
                    aspectRatioX.setText(" " + progress);
                } catch (IllegalArgumentException e) {
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        // Sets aspectRatioY
        final TextView aspectRatioY = (TextView) findViewById(R.id.aspectRatioY);

        aspectRatioYSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar aspectRatioYSeek, int progress, boolean fromUser) {
                try {
                    mAspectRatioY = progress;
                    cropImageView.setAspectRatio(mAspectRatioX, progress);
                    aspectRatioY.setText(" " + progress);
                } catch (IllegalArgumentException e) {
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });


        // Sets up the Spinner
        showGuidelinesSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                cropImageView.setGuidelines(i);
            }

            public void onNothingSelected(AdapterView<?> adapterView) {
                return;
            }
        });*/

        final Button cropButton = (Button) findViewById(R.id.Button_crop);
        cropButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
             //   croppedImage = cropImageView.getCroppedImage();
             //   ImageView croppedImageView = (ImageView) findViewById(R.id.croppedImageView);
             //   croppedImageView.setImageBitmap(croppedImage);
            	diyScale=0;
                croppedImage = cropImageView.getCroppedImage();
              
              //  croppedImage=AbImageUtil.getScaleBitmap(croppedImage,0.8f);
                AbLogUtil.e("onActivityResult-showBitmap-white-height", croppedImage.getWidth()+"--"+croppedImage.getHeight());
                File file= ImageUtil.BitmapToFileNoSave(croppedImage);
                Intent intent=new Intent(); 
            	intent.putExtra(TagCropBitmap, file.getAbsolutePath());
				setResult(RESULT_OK, intent);
            	finish();
            	//taskLoadShopImage(file);            	
            }
        });
        initBitmap(cropImageView);

    }

    /*
     * Sets the font on all TextViews in the ViewGroup. Searches recursively for
     * all inner ViewGroups as well. Just add a check for any other views you
     * want to set as well (EditText, etc.)
     */
    public void setFont(ViewGroup group, Typeface font) {
        int count = group.getChildCount();
        View v;
        for (int i = 0; i < count; i++) {
            v = group.getChildAt(i);
            if (v instanceof TextView || v instanceof EditText || v instanceof Button) {
                ((TextView) v).setTypeface(font);
            } else if (v instanceof ViewGroup)
                setFont((ViewGroup) v, font);
        }
    }

    /**
	 * 上传商品联盟图
	 */
	private void taskLoadShopImage(final File file) {
		//"p","supId","limitvalue","sizevalue"
		/*HashMap<String, File> fileMap=new HashMap<String, File>();
		fileMap.put("lolImg", file);
		RequestServerManager.getInstance().handleMethod(GUrl.WEBSERVICE2,
				RequestServerManager.getInstance().getRequestParams(
						GUrlApi.lolImg,fileMap,GUrl.WEBSERVICE_CPU_GSUP,AppConfig.getUser().getObjId()), 
						BaseResponse.class, 
				new ICallBackForRequestServer<BaseResponse>() {

					@Override
					public void onSuccess(BaseResponse result) {
						AbLogUtil.e("taskGetActCount", "onFail--"+result);
					}

					@Override
					public void onFail(int type, String errorMsg, String json) {
						AbLogUtil.e("taskGetActCount", "onFail--"+errorMsg);
						//updateUI(null, type);
					}

					
				});*/


	}
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }
	  public void initBitmap(CropImageView cropImageView) {
		  
	        String imgPath = getIntent().getStringExtra(TagCropBitmap);
//	        AbLogUtil.e("imgPath", imgPath);
	        File file = new File(imgPath);
	        //拍照选择的角度
	       
	        
	        if (file.exists()) {
	        	int degree=readPictureDegree(imgPath);
	        	//普通图片
	        	if (degree==0) {
		        	Bitmap bitmap=getOptionsScaleBitmap(file,App.getInstance().screenWidth,true);
		        	cropImageView.setImageBitmap(bitmap);
				}
	        	//拍照后的图片
	        	else
				{
					  BitmapFactory.Options opts=new BitmapFactory.Options();//获取缩略图显示到屏幕上
		                opts.inSampleSize=2;
		                Bitmap cbitmap=BitmapFactory.decodeFile(file.getAbsolutePath(),opts);
		                /**
		                 * 把图片旋转为正的方向
		                 */
		             //   Bitmap newbitmap = rotaingImageView(degree, cbitmap);
		                cbitmap=rotate(cbitmap, readPictureDegree(imgPath));
		             cropImageView.setImageBitmap(cbitmap);
				}
	        
	        } else {
	            finish();
	        }
		//  cropImageView.setImageResource(R.drawable.test_back);
	  }
	  public static int readPictureDegree(String path) {
		  int degree = 0;
		  try {
		  ExifInterface exifInterface = new ExifInterface(path);
		  int orientation = exifInterface.getAttributeInt(
		  ExifInterface.TAG_ORIENTATION,
		  ExifInterface.ORIENTATION_NORMAL);
		  switch (orientation) {
		  case ExifInterface.ORIENTATION_ROTATE_90:
		  degree = 90;
		  break;
		  case ExifInterface.ORIENTATION_ROTATE_180:
		  degree = 180;
		  break;
		  case ExifInterface.ORIENTATION_ROTATE_270:
		  degree = 270;
		  break;
		  }
		  } catch (IOException e) {
		  e.printStackTrace();
		  }
		  return degree;
	  }
	  public static Bitmap rotate(Bitmap b, int degrees) {
		  if(degrees==0){
		  return b;
		  }
		  if (degrees != 0 && b != null) {
		  Matrix m = new Matrix();
		  m.setRotate(degrees, (float) b.getWidth() ,
		  (float) b.getHeight() );
		  try {
		  Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
		  b.getHeight(), m, true);
		  if (b != b2) {
		  b.recycle(); // Android开发网再次提示Bitmap操作完应该显示的释放
		  b = b2;
		  }
		  } catch (OutOfMemoryError ex) {
		  // Android123建议大家如何出现了内存不足异常，最好return 原始的bitmap对象。.
		  }
		  }
		  return b;
	  }
	  public static Bitmap getOptionsScaleBitmap(File file,int sWidth,boolean isFullWidth)
	  {
			BitmapFactory.Options opts = new BitmapFactory.Options();
    		// 设置为true,decodeFile先不创建内存 只获取一些解码边界信息即图片大小信息
    		opts.inJustDecodeBounds = true;
    		BitmapFactory.decodeFile(file.getPath(), opts);

    		// 获取图片的原始宽度
    		int srcWidth = opts.outWidth;
    		// 获取图片原始高度
    		int srcHeight = opts.outHeight;
    	    int desiredWidth;
    	    int desiredHeight;
          //判断宽度是否全屏
            if (isFullWidth) {
                // 期望的宽度
                desiredWidth = sWidth;
                // 期望的高度
                desiredHeight = sWidth * srcHeight / srcWidth;
            }else {
                if (srcWidth>srcHeight)
                {
                    desiredWidth=sWidth;
                    desiredHeight=sWidth * srcHeight / srcWidth;
                }else {
                    desiredHeight=sWidth;
                    desiredWidth=sWidth*srcWidth/srcHeight;
                }
            }
        	//float fscale=Math.min((float)AppConfig.getInstance().screenWidth/(float)bitMapOriginal.getWidth(), (float)AppConfig.getInstance().screenHeight/(float)bitMapOriginal.getHeight());
        	//Bitmap bitmap=AbImageUtil.getCutBitmap(file,desiredWidth,desiredHeight);
        	return AbImageUtil.getScaleBitmap(file,desiredWidth,desiredHeight);
        	
	  }

}
